<template>
  <el-dialog :model-value="dialogData.isShow" :title="'发布'" @close="closeDialog" draggable>
    <el-form :model="form" ref="formRef" :rules="rules" label-width="90px">
      <el-row :gutter="10">
        <el-col :span="24">
          <el-form-item label="网页地址" prop="url">
            <el-input type="textarea" v-model="form.url" maxlength="2048" disabled placeholder="请输入网页地址"/>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="图片地址" prop="imgUrl">
            <el-input type="textarea" v-model="form.imgUrl" maxlength="2048" disabled placeholder="请输入图片地址"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span="24">
          <el-form-item label="标题" prop="title">
            <el-input v-model="form.title" maxlength="255" placeholder="请输入标题"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span="24">
          <el-form-item label="文章内容" prop="articleContent">
            <div v-if="WangEditorShow">
              <WangEditor v-model="form.articleContent"/>
            </div>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item label="分类">
            <el-tree-select
                v-model="formSelect.categoryIds"
                :data="categoryList"
                multiple
                check-strictly
                :render-after-expand="false"
                show-checkbox
                style="width: 240px"
            />
          </el-form-item>
        </el-col>
        <el-col v-if="topicsReqStatus" :span="12">
          <el-form-item label="专题">
            <el-select
                v-model="formSelect.topicsIds"
                multiple
                placeholder="请选择专题"
                style="width: 240px"
            >
              <el-option
                  v-for="item in topicsList"
                  :key="item.id"
                  :label="item.title"
                  :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col v-if="expertReqStatus" :span="12">
          <el-form-item label="专家">
            <el-select
                v-model="formSelect.expertIds"
                multiple
                placeholder="请选择专家"
                style="width: 240px"
            >
              <el-option
                  v-for="item in expertList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="submit" :loading="releaseLoading">发布</el-button>
        <el-button @click="closeDialog">取消</el-button>
      </div>
    </template>
  </el-dialog>
</template>


<script setup lang="ts">
import {ElMessage, FormInstance, FormRules} from "element-plus";
import {getCrawlerData, release} from "@/api/app/crawlerData";
import {getAllArticleCategoryTreeList} from "@/api/app/articleCategoty";
import {getArticleTopicsList} from "@/api/app/articleTopics";
import {getExpertList} from "@/api/app/expert";

const formRef = ref<FormInstance>()

const releaseLoading = ref(false)


const emits = defineEmits<{
  (event: 'refresh'): void
}>()

// 表单
let form: any = ref({
  id: null,
  url: '',
  title: '',
  imgUrl: '',
  articleContent: '',
  urlDetail: '',
  crawlerDate: '',
});

let formSelect: any = ref({
  categoryIds: [],
  topicsIds: [],
  expertIds: [],
})

// 效验规则
const rules = reactive<FormRules>({})
const WangEditorShow = ref(false)
const expertReqStatus = ref(false)
const topicsReqStatus = ref(false)
// 获取详情
const getDetails = (id: string) => {
  getCrawlerData(id).then(res => {
    console.log(res)
    form.value.id = res.id
    form.value.url = res.url
    form.value.title = res.title
    form.value.imgUrl = res.imgUrl
    form.value.articleContent = res.articleContent
    form.value.urlDetail = res.urlDetail
    form.value.crawlerDate = res.crawlerDate
    WangEditorShow.value = true
  })
}

// 弹框数据
const dialogData = reactive({
  isShow: false,
  id: null
})

// 打开弹框
const openReleaseDialog = async (id: string) => {
  dialogData.isShow = true;
  dialogData.title = '发布'
  getDetails(id);
  getCategoryList();
  getTopicsPage();
  getAllExpertList({})
}

// 关闭弹框
const closeDialog = () => {
  dialogData.isShow = false;
  form.value = {};
  formSelect.value = {};
  WangEditorShow.value = false
  expertReqStatus.value = false
  topicsReqStatus.value = false
}

// 提交
const submit = async () => {
  if (!formRef.value) return;
  releaseLoading.value = true;

  try {
    // 使用 await 等待表单验证
    const valid = await formRef.value.validate();

    if (valid) {
      form.value.categoryIds = formSelect.value.categoryIds
      form.value.topicsIds = formSelect.value.topicsIds
      form.value.expertIds = formSelect.value.expertIds
      const data = {...form.value};
      await release(data);
      ElMessage.success('操作成功');
      closeDialog();
      emits('refresh');
    }
  } catch (error) {
    // 处理错误（验证失败或请求异常）
    ElMessage.error('操作失败');
  } finally {
    releaseLoading.value = false; // 无论成功失败，关闭 loading
  }
}

const categoryList = ref([])

const getCategoryList = () => {
  getAllArticleCategoryTreeList({}).then(res => {
    if (res.length) {
      let data = [...res]

      function fun(dataList: any[]) {
        dataList.map(item => {
          if (item.children) fun.call(this, item.children)
          Object.assign(item, {value: item.id, label: item.categoryName})
        })
      }

      fun.call(this, data)
      categoryList.value = data
    }
  })
}

const topicsList = ref([])

const getTopicsPage = () => {
  getArticleTopicsList({}).then(res => {
    topicsList.value = res
    topicsReqStatus.value = true
  })
}

const expertList = ref([])

const getAllExpertList = (data: any) => {
  getExpertList(data).then(res => {
    expertList.value = res
    expertReqStatus.value = true
  })
}


defineExpose({
  openReleaseDialog,
});
</script>

<style scoped></style>
